import { tagAliasReg, tagVariableReg } from '../../reg-exp';

/**
 * 上下文标签项
 *
 * @author chitanda
 * @date 2022-01-13 09:01:05
 * @export
 * @class ContextTag
 */
export class ContextTag {
  /**
   * each or with 变量名称
   *
   * @author chitanda
   * @date 2022-01-13 09:01:01
   * @type {string}
   */
  variable: string = '';
  /**
   * each or with 别名变量名称
   *
   * @author chitanda
   * @date 2022-01-13 09:01:12
   * @type {string}
   */
  alias: string = '';
  /**
   * 起始标签
   *
   * @author chitanda
   * @date 2022-01-13 10:01:03
   * @type {boolean}
   */
  start: boolean = false;
  /**
   * 结束标签
   *
   * @author chitanda
   * @date 2022-01-13 10:01:14
   * @type {boolean}
   */
  end: boolean = false;
  /**
   * 文本所在位置
   *
   * @author chitanda
   * @date 2022-01-13 11:01:34
   * @readonly
   * @type {number}
   */
  get index(): number {
    return this.exec.index;
  }
  /**
   * 文本的长度
   *
   * @author chitanda
   * @date 2022-01-13 17:01:18
   * @readonly
   * @type {number}
   */
  get length(): number {
    return this.exec[0].length;
  }
  /**
   * Creates an instance of ContextTag.
   *
   * @author chitanda
   * @date 2022-01-13 09:01:26
   * @param {('each' | 'with')} type 标签类型
   * @param {RegExpExecArray} exec 正则匹配结果
   */
  constructor(public type: 'each' | 'with' | 'eachEnd' | 'withEnd', public exec: RegExpExecArray) {
    if (type === 'each' || type === 'with') {
      this.variable = exec[1];
      const result = tagAliasReg.exec(this.variable);
      if (result && result.length > 0) {
        this.alias = result[1];
        this.variable = tagVariableReg.exec(this.variable)![1];
      }
      this.start = true;
    } else {
      this.end = true;
    }
  }

  /**
   * 是否使用了别名
   *
   * @author chitanda
   * @date 2022-01-13 15:01:56
   * @return {*}  {boolean}
   */
  isAlias(): boolean {
    return !!(this.alias && this.alias !== '');
  }
}
